package com.fh.login;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.member.entity.Member;
import com.fh.member.service.MemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import utils.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("login")
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;
    @Resource
    private HttpServletRequest request;

    @GetMapping("/sendMsg")
    public ResultObj getMsgCode(String phone){
        if (StrUtil.isBlank(phone)){
            return ResultObj.error(ResultCode.PHONE_ISNULL);
        }
        String code = SendMsg.sendMsg(phone);
        if (StrUtil.isBlank(code)){
            return ResultObj.error(ResultCode.CODE_ISNULL);
        }
        redisTemplate.opsForValue().set(RedisKey.getCodeKey(phone),code,1, TimeUnit.MINUTES);
        return ResultObj.success(code);
    }

    @PostMapping("login")
    public ResultObj login(String code,String phone){
        if (StrUtil.isBlank(code) || StrUtil.isBlank(phone)){
            ResultObj.error(ResultCode.CODE_PHONE_ISNULL);
        }
     /*   String codeRedis = (String) redisTemplate.opsForValue().get(RedisKey.getCodeKey(phone));
        if (StrUtil.isBlank(codeRedis)){
            return ResultObj.error(ResultCode.CODE_PHONE_Error);
        }*/

        if (!StrUtil.equals("123123",code)){
            return ResultObj.error(ResultCode.CODE_Error);
        }

        //判断手机号有没有注册
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        Member member = memberService.getOne(wrapper);
        if (member == null){
            member = new Member();
            member.setPhone(phone);
            member.setCreateTime(new Date());
            member.setNickname(phone);
            memberService.save(member);

        }
        redisTemplate.delete(RedisKey.getCodeKey(phone));
        String token = JwtUtil.createToken(phone);
        redisTemplate.opsForValue().set("userId",String.valueOf(member.getId()));

        return ResultObj.success(token);
    }
    @GetMapping("{token}")
    public ResultObj checktoken(@PathVariable("token")String token){
        ResultObj resultObj = JwtUtil.getClaimsFromToken(token);
        return ResultObj.success(resultObj.getCode());
    }

}
